import { View, Text, Image, Input, Textarea } from "@tarojs/components";
import Taro, { useDidShow, useLoad } from "@tarojs/taro";
import { Button, Cell, CellGroup, Empty, NavBar, Overlay, Picker } from "@nutui/nutui-react-taro";
import { Share, More, Cart, ArrowLeft, Close } from '@nutui/icons-react-taro'
import { c } from "../../common";
import { useEffect, useState } from "react";
import { getParams, navigateTo } from "../../common/_";

import { selectExamDetail, startExam } from "../../api/ceshi";
import SelectItem from "../../components/selectItem";
import InputItem from "../../components/inputItem";
import CustomCell from "../../components/custom-cell";
import dayjs from "dayjs";
import { iconCloseRed, iconSuccessGreen, iconWait, iconWaitBlue } from "../../assets/files";
import { audit, getTrainingInfoWait } from "../../api/apply";
import { getSystemDictValue, getSystemEnumValue } from "../../utils/globalData";
import { baseUrl } from "../../utils/request";
import EditModal from "./components/edit-modal";
import "./index.scss";

export default function Mine() {

  const [successVisible, setSuccessVisible] = useState(false)
  const [isVisible2, setIsVisible2] = useState(false)
  const [isAudit, setIsAudit] = useState(false)
  const [trainingTime, setTrainingTime] = useState("")
  const [leturer, setLeturer] = useState("")
  const [auditReason, setAuditReason] = useState("")

  const [auditType, setAuditType] = useState("")
  const [timeList, setTimeList] = useState([])
  const [detail, setDetail] = useState({})
  const [shenqStatus, setShenqStatus] = useState([
    {
      id: 1,
      name: "审核中",
      color: '#FF8916',
      bgColor: 'rgba(255, 212, 148, 0.3)',
      icon: iconWait
    },
    {
      id: 2,
      name: "待培训",
      color: '#6486FF',
      bgColor: 'rgba(148, 197, 255, 0.5)',
      icon: iconWaitBlue
    },
    {
      id: 3,
      name: "已拒绝",
      color: '#FF1616',
      bgColor: 'rgba(255, 148, 148, 0.5)',
      icon: iconCloseRed
    },
    {
      id: 4,
      name: "已培训",
      color: 'rgba(7, 193, 96, 1)',
      bgColor: 'rgba(176, 255, 214, 0.35)',
      icon: iconSuccessGreen
    },
  ]);

  useEffect(() => {
    getGennerDate()
    console.log("audit", getParams().isAudit);
    setIsAudit(getParams().isAudit || false)
    getDetail(getParams().id)
  }, [])

  const getDetail = async (id) => {
    const { success, data } = await getTrainingInfoWait({ id:id })
    if (success) {
      setDetail(data)
    }
  }

  const getGennerDate = () => {
    const today = dayjs();
    let dates = [];
    for (let i = 1; i <= 30; i++) {
      const date = today.add(i - 1, 'day').format('MM-DD'); // i + 1 因为起始点是后两天
      dates.push({ text: date, value: date });
    }
    setTimeList([dates, [
      { text: "09:00", value: "09:00" },
      { text: "10:00", value: "10:00" },
      { text: "11:00", value: "11:00" },
      { text: "15:00", value: "15:00" },
      { text: "16:00", value: "16:00" },
      { text: "17:00", value: "17:00" }
    ]])
  }

  function matchType(type) {
    for (let index = 0; index < shenqStatus.length; index++) {
      const element = shenqStatus[index];
      if (element.id === type) {
        return element
      }
    }
  }

  const shenhe = (type) => {
    setAuditType(type)
    setTrainingTime(detail.trainingTime)
    setSuccessVisible(true)
  }

  const changePicker = (list, option, columnIndex) => {
    console.log(columnIndex, option)
  }

  const auditSubmit = async (leturerName, leturer) => {

    // Taro.navigateBack()
    //   Taro.eventCenter.trigger('reAuditList', {});
    //   return;

    const { success } = await audit({
      auditReason,
      auditState: auditType,
      id: detail?.id,
      leturer,
      // leturerName,
      trainingTime: trainingTime.length === 19 ? trainingTime : dayjs().format('YYYY-')+trainingTime+":00"
    })

    if (success) {
      setSuccessVisible(false)
      Taro.navigateBack()
      Taro.eventCenter.trigger('reAuditList', {});
      Taro.showToast({
        title: '提交成功',
        icon: 'none'
      })
    } else {
      Taro.showModal({
        content: msg
      })
    }
  }

  const previewImage = (curUrl) => {
    let arr = []
    detail.list.forEach(v => {
      arr.push(baseUrl + v.sysFileUrl)
    })
    Taro.previewImage({
      current: curUrl, // 当前显示图片的http链接
      urls: arr, // 需要预览的图片http链接列表
    });
  }

  return (
    <View className="wrap">
      <View className="topContent">
        <Image src={detail?.auditState && matchType(detail?.auditState).icon} className="waitSty" />
        <Text className="shenqingStatus">
          {detail?.auditState && matchType(detail?.auditState).name}
        </Text>
      </View>
      <View className="formWrap">
        <CustomCell label="单位所在辖区" value={getSystemDictValue(13, detail?.jurisdiction)?.name} />
        <CustomCell label="申请类别" value={getSystemDictValue(77, detail?.category)?.name} />
        <CustomCell label="申请单位名称" value={detail?.enterpriseName} />
        <CustomCell label="培训人数" value={detail?.number} />
        <CustomCell label="联系人姓名" value={detail?.contactName} />
        <CustomCell label="联系电话" value={detail?.phone} valueStyle={{ color: 'blue' }} onClick={() => { Taro.makePhoneCall({ phoneNumber: detail?.phone }) }} />
        <CustomCell label="培训时间" value={detail?.trainingTime?.substr(0, 16)} />
        <CustomCell label="备注" value={detail?.remark || '--'} />
        <CustomCell label="创建时间" value={detail?.createdAt} />
        {/* <CustomCell 
        label="培训主讲人" 
        valueStyle={{ color: 'blue' }}
        value={detail?.leturerName ? detail?.leturerName+" "+detail?.leturerPhone : '--'}
        onClick={() => {
            if(detail?.leturerPhone){
              Taro.makePhoneCall({ phoneNumber: detail?.leturerPhone })
            }
            return;
           
           }} 
         /> */}
        {/* {
          detail?.auditState == 3 &&
          <CustomCell label="审核意见" value={detail?.auditReason || '--'} />
        } */}

        <CustomCell label="审核意见" value={detail?.auditReason || '--'} />

        {
          isAudit &&
          <View className="picWrap">
            <Text className="pictit">图片</Text>
            <View className="imgListWrap">
              {
                detail?.list?.map(v => {
                  return (
                    <Image onClick={() => previewImage(baseUrl + v.sysFileUrl)} className="imgShow" src={baseUrl + v.sysFileUrl} />
                  )
                })
              }
            </View>
          </View>
        }


      </View>
      {
        isAudit && detail?.auditState == 1 &&
        <View className="btnWrap1">
          <View>
            <Button block onClick={(e) => shenhe(3)} size="large" type="info" style={{}}>拒绝申请</Button>
          </View>
          <View>
            <Button block onClick={(e) => shenhe(2)} size="large" type="success" style={{}}>同意申请</Button>
          </View>
        </View>
      }

      <Picker
        title="选择培训时间"
        visible={isVisible2}
        options={timeList}
        onClose={() => setIsVisible2(false)}
        onChange={changePicker}
        onConfirm={(options, values) => {
          setTrainingTime(values[0] + ' ' + values[1])
        }}
      />

      <EditModal
        auditType={auditType}
        trainingTime={trainingTime}
        auditReason={auditReason}
        visible={successVisible}
        close={() => { 
          setSuccessVisible(false)
          setAuditReason("")
         }}
        onChangeTime={(time) => {
          setTrainingTime(time)
        }}
        onChangeAuditReason={(text)=>{
          setAuditReason(text)
        }}
        submit={(leturerName, leturer) => {
          auditSubmit(leturerName, leturer)
        }}
      />
    </View>
  );
}
